/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.web.rest;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.retabel.persistence.entity.document.ContentTypeEnum;
import org.retabel.persistence.entity.document.ExportConfiguration;
import org.retabel.service.manager.ExportConfigurationManager;
import xsd.exportconfigurations.ExportConfigurationList;
import xsd.exportconfigurations.ExportConfigurations;
import xsd.exportconfigurations.ObjectFactory;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

/**
 * Document configuration REST interface implementation.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 10:19 16.07.11
 *
 * @author Peter Herber
 * @version 1.0
 */
@Path("/config/exports/")
@Stateless
public class ExportConfigurationServiceBean extends RestServiceBean {

    @EJB
    private ExportConfigurationManager exportConfigurationManager;

    /**
     * Retrieve a ranged list of available export configurations.
     *
     * @param first   the index of the first export configuration to retrieve.
     * @param maxRows the maximum number of matches to retrieve.
     * @return xml containing the list of export configurations matching the given search criteria.
     */
    @GET
    @Produces(MediaType.TEXT_XML)
    public Response getExportConfigurations(@QueryParam("first") Integer first, @QueryParam("maxRows") Integer maxRows) {
        int maxRowsWithFallback = maxRows != null ? maxRows : getDefaultMaxResultsPerPage();
        int firstWithFallback = first != null ? first : 0;

        int countExportConfigurations = exportConfigurationManager.count();
        ExportConfiguration[] exportConfigurations = exportConfigurationManager.findRange(firstWithFallback,
                                                                                          maxRowsWithFallback);

        ObjectFactory of = new ObjectFactory();

        ExportConfigurations result = of.createExportConfigurations();
        result.setStart(firstWithFallback);
        result.setRows(exportConfigurations.length);
        result.setCount(countExportConfigurations);

        ExportConfigurationList exportConfigurationList = of.createExportConfigurationList();
        result.setList(exportConfigurationList);

        for (ExportConfiguration exportConfiguration : exportConfigurations) {
            xsd.exportconfigurations.ExportConfiguration resultExportConfiguration = of.createExportConfiguration();
            resultExportConfiguration.setName(exportConfiguration.getName());
            resultExportConfiguration.setContentType(exportConfiguration.getContentType().toString());
            resultExportConfiguration.setLocation(exportConfiguration.getLocation());

            exportConfigurationList.getExportConfiguration().add(resultExportConfiguration);
        }

        return Response.ok(result).build();
    }

    /**
     * Add a new export configuration.
     *
     * @param name    the unique export name to add.
     * @param uriInfo the uri info context used for logging purposes.
     * @return plain/text log lines.
     */
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_PLAIN)
    public Response newExportConfiguration(@FormParam("name") String name, @FormParam("contentType") String contentType,
                                           @FormParam("location") String location, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);

        response.println("Attempting to store export configuration: " + name);

        ContentTypeEnum contentTypeEnum = ContentTypeEnum.valueOf(contentType);

        if (contentTypeEnum == null) {
            return Response.status(HttpStatus.SC_BAD_REQUEST).entity(
                "Unknown content type: " + contentType + "accepted values [" + StringUtils.join(ContentTypeEnum.values(), ",")
                + "]").build();
        }

        exportConfigurationManager.store(name, contentTypeEnum, location);

        return response.getResponse();
    }

    /**
     * Delete an export configuration by it's unique name.
     *
     * @param name    the unique export configuration name.
     * @param uriInfo the uri info context used for logging purposes.
     * @return plain/text log lines.
     */
    @DELETE
    @Path("/{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response deleteExportConfiguration(@PathParam("name") String name, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);

        response.println("Deleting export configuration: " + name);

        exportConfigurationManager.remove(name);

        return response.getResponse();
    }
}
